//index.js
const request = require("../../../utils/request.js");
const CountryCode = require("../../../utils/countryCode.js")
const util = require("../../../utils/util.js")
const app = getApp()
Page({
  data: {
    scrollTop: 0,
    scrollHeight: 0,
    buyNow: false,
    chooseCate: false,
    cateSelected: false,
    selectedIdx: -1,
    itemNum: 1,
    animationData: {},
    selectedCate: "",
    buttonText: "选择颜色分类等",
    storeInfo: [],
    itemDescImgs: [],
    cates: [],
    goodImgUrls: [],
    currentTab: 0,
    cycleImgsFeatures: {
      indicatorDots: true,
      autoplay: false,
      interval: 5000,
      duration: 1000,
    },
    goods: {},
    twoNewestComments: [],
    //购物车总数
    totalNum: 0,
    hasCarts: false,
    goodId: -1
  },
  onLoad: function(e) {
    var that = this;
    console.log(e);
    var goodId = e.goodId;
    that.setData({
      goodId: goodId
    })
    var url = request.URL + "/goodDetail"
    request.request({
      url: url,
      data: {
        goodId: goodId
      },
      success: function(res) {
        console.log(res.data);
        var goodInfo = res.data.good;
        var commentLevelAvg = res.data.commentLevelAvg;
        goodInfo.commentLevelAvg = commentLevelAvg;
        var storeInfo = res.data.store;
        var comments = res.data.comment.slice(0, 2);
        for (var i = 0; i < comments.length; i++) {
          var commentTime = util.formatTime(parseInt(comments[i].commentTime) / 1000);
          comments[i].commentTime = commentTime.split(' ')[0];
        }
        //处理商品图片字符串或者商品图片数组
        var goodImgs = goodInfo.goodImgArray;
        var goodImgsArr = util.string2Array(goodImgs);
        //处理商品详情图字符串获得商品详情图数组
        var itemDescImgs = goodInfo.goodDesImgArray;
        var itemDescImgsArr = util.string2Array(itemDescImgs);
        //获得商品分类数组
        var itemCates = goodInfo.standardArray;
        var itemCatesArr = util.string2Array(itemCates);
        //通过countryId得到相应的国家名和国旗
        var countryId = storeInfo.countryId;
        var countryName = "";
        var countryImgUrl = "";
        var countryInfo = CountryCode.getCountryInfo(countryId) || null;
        if (countryInfo == null) {
          storeInfo.countryName = "其它";
          storeInfo.countryImgUrl = countryImgUrl;
        } else {
          storeInfo.countryName = countryInfo.chineseName;
          storeInfo.countryImgUrl = countryInfo.img;
        }
        console.log(goodInfo)
        that.setData({
          goods: goodInfo,
          goodImgUrls: goodImgsArr,
          itemDescImgs: itemDescImgsArr,
          cates: itemCatesArr,
          storeInfo: storeInfo,
          twoNewestComments: comments
        })
        console.log(comments)
      },
      fail: function() {
        request.showFailInfo();
      }
    })
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      },
    });
  },
  onShow: function() {
    var that = this;
    var shopTrolley = {}
    var url = request.URL + "/shopTrolley";
    request.request({
      url: url,
      data: {
        userId: 1
      },
      success: function(res) {
        var shopTrolleyData = res.data;
        var total = 0;
        for (var key in shopTrolleyData) {
          var shopTrolleyArr = shopTrolleyData[key];
          for (var i = 0; i < shopTrolleyArr.length; i++) {
            var goodNum = shopTrolleyArr[i].goodCnt;
            total += parseInt(goodNum);
          }
        }
        if (total > 0) {
          that.setData({
            totalNum: total,
            hasCarts: true,
          })
        }
      },
      fail: function() {
        request.showFailInfo()
      }
    })
  },
  scroll: function(e, res) {
    if (e.detail.scrollTop > 300) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  goTop: function(e) {
    this.setData({
      scrollTop: 0
    });
  },
  buyNow: function() {
    var that = this;
    if (that.data.chooseCate) {
      that.hideModal();
    }
    if (that.data.hasSelection) {
      that.setData({
        buyNow: true
      });
    } else {
      that.showDetailsSheet();
    }
  },
  hide_dialog: function() {
    var that = this;
    that.setData({
      buyNow: false
    });
  },
  /**进入订单确认页 */
  toConfirmOrderPage: function() {
    var that = this;
    var orderItemsArr = [];
    var goodsArr = [];
    var goodObj = new Object();
    var storeObj = new Object();
    var goodInfo = that.data.goods;
    var storeInfo = that.data.storeInfo;
    /**userId暂时为1 */
    var userId = 1;
    var storeId = goodInfo.storeId;
    var goodId = goodInfo.goodId;
    var storeName = storeInfo.storeName;
    var goodName = goodInfo.goodName;
    var goodPrice = goodInfo.goodPrice;
    var transCost = goodInfo.transCost;
    var goodImgUrl = that.data.goodImgUrls[0];
    var standard = that.data.selectedCate;
    var goodCnt = parseInt(that.data.itemNum);

    var fromItemPage = true;

    goodObj.goodCnt = goodCnt;
    goodObj.goodId = goodId;
    goodObj.goodImgUrl = goodImgUrl;
    goodObj.goodName = goodName;
    goodObj.goodPrice = goodPrice;
    goodObj.standard = standard;
    goodObj.storeId = storeId;
    goodObj.storeName = storeName;
    goodObj.transCost = transCost;
    goodObj.userId = userId;
    goodsArr.push(goodObj);
    storeObj.storeId = storeId;
    storeObj.storeName = storeName;
    storeObj.goodsArr = goodsArr;
    orderItemsArr.push(storeObj);
    orderItemsArr.fromItemPage = fromItemPage;
    app.globalData.orderItemsArr = orderItemsArr;
    wx.navigateTo({
      url: '/pages/order_list/order_confirm/order_confirm'
    })
  },
  //查看全部评价
  accessAllCommments: function(e) {
    var that = this;
    var goodId = that.data.goods.goodId;
    var goodName = that.data.goods.goodName;
    wx.navigateTo({
      url: '/pages/details/comment_details/comment_details' + '?goodId=' + goodId + '&goodName=' + goodName,
    })
  },
  // 加入购物车
  addToCart: function(e) {
    const that = this;
    if (that.data.chooseCate) {
      if (that.data.hasSelection) {
        const goodId = that.data.goods.goodId;
        var selectedNum = that.data.itemNum;
        var selectedCate = that.data.selectedCate;
        let total = that.data.totalNum;
        var url = request.URL + "/shopTrolley/add";
        request.request({
          url: url,
          data: {
            userId: 1,
            goodId: goodId,
            standard: selectedCate,
            goodCnt: parseInt(selectedNum)
          },
          success: function(res) {
            console.log(res);
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              success: function() {
                wx.hideToast();
              }
            })
            setTimeout(function() {
              that.setData({
                scaleCart: false,
                hasCarts: true,
                totalNum: total + selectedNum
              })
            }, 200);
          },
          fail: function() {
            request.showFailInfo()
          }
        })
      } else {
        wx.showToast({
          title: '请选择一个类别',
          image: '/images/warning_sign.png',
          icon: 'none',
          duration: 2000
        })
      }

    } else {
      if (that.data.hasSelection) {
        const goodId = that.data.goods.goodId;
        var selectedNum = that.data.itemNum;
        var selectedCate = that.data.selectedCate;
        let total = that.data.totalNum;
        var url = request.URL + "/shopTrolley/add";
        request.request({
          url: url,
          data: {
            userId: 1,
            goodId: goodId,
            standard: selectedCate,
            goodCnt: parseInt(selectedNum)
          },
          success: function(res) {
            console.log(res);
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              success: function() {
                wx.hideToast();
              }
            })
            setTimeout(function() {
              that.setData({
                scaleCart: false,
                hasCarts: true,
                totalNum: total + selectedNum
              })
            }, 200);
          },
          fail: function() {
            request.showFailInfo()
          }
        })
      } else {
        that.showDetailsSheet();
      }
    }


  },

  //弹出底部分类内容栏
  showDetailsSheet: function(e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 250,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(500).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      chooseCate: true
    })

    //console.log(that.data.chooseCate);
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  //点击关闭弹出的底部类别栏
  hideModal: function(e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(1000).step()
    that.setData({
      animationData: animation.export()

    })
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        chooseCate: false
      })
    }, 200)
  },

  //选择商品的分类颜色等
  selectCate: function(e) {
    var that = this;
    var idx = e.currentTarget.dataset.id;
    var selected = that.data.cateSelected;
    if (selected) {
      selected == false;
    } else {
      selected == true;
      that.setData({
        selectedIdx: idx
      })

      that.setData({
        selectedCate: that.data.cates[idx]
      })
      that.setData({
        buttonText: "已选：" + that.data.selectedCate + " 数量：" + that.data.itemNum,
        hasSelection: true
      })
    }
  },

  //拖动条目实时更新输入框
  changeItemNum: function(e) {
    var that = this;
    console.log(e.detail.value);
    that.setData({
      itemNum: parseInt(e.detail.value)
    })
    that.setData({
      buttonText: "已选：" + that.data.selectedCate + " 数量：" + that.data.itemNum,
    })
  },
  //加号加一物品
  addOne: function(e) {
    var that = this;
    var itemNum = that.data.itemNum;
    itemNum += 1;
    that.setData({
      itemNum: itemNum
    })
    that.setData({
      buttonText: "已选：" + that.data.selectedCate + " 数量：" + that.data.itemNum,
    })
  },

  //减号加一物品
  minusOne: function(e) {
    var that = this;
    var itemNum = that.data.itemNum;
    itemNum -= 1;
    if (itemNum >= 1) {
      that.setData({
        itemNum: itemNum
      })
    } else {
      that.setData({
        itemNum: 1
      })
    }
    that.setData({
      buttonText: "已选：" + that.data.selectedCate + " 数量：" + that.data.itemNum,
    })
  },


  accessToShopPage: function(e) {
    var that = this;
    var storeId = that.data.storeInfo.storeId;
    wx.navigateTo({
      url: '/pages/details/shop_details/shop_details' + '?storeId=' + storeId
    })
  },
  /**点击进入购物车 */
  accessToShopCart: function(e) {
    wx.switchTab({
      url: '/pages/shopcart/shopcart',
    })
  },
  // /**access in to shop customer service chat page */
  // toCustomerServiceChatPage: function (e) {
  //   var storeId = e.currentTarget.dataset.storeid;
  //   var storeName = e.currentTarget.dataset.storename;
  //   var goodId = e.currentTarget.dataset.goodid;
  //   var goodName = e.currentTarget.dataset.goodname;
  //   var goodImg = encodeURIComponent(e.currentTarget.dataset.goodimg);
  //   console.log(goodImg);
  //   var goodPrice = e.currentTarget.dataset.goodprice;
  //   wx.navigateTo({
  //     url: '/pages/customer_service_chat/customer_service_chat?storeId=' + storeId + '&goodId=' + goodId + '&goodName=' + goodName + '&goodPrice=' + goodPrice + '&goodImg=' + goodImg + '&storeName=' + storeName
  //   })
  // },
  //转发小程序
  onShareAppMessage: function() {
    var that = this;
    var item = that.data.goods;
    var itemName = item.goodName;
    var goodId = that.data.goodId;
    //url = "../../pages/details/item_details/item_details?goodId=" + goodId;
    return {
      title: itemName,
      path: '/pages/details/item_details/item_details?goodId=' + goodId,
      success: function(res) {
        //转发成功
        wx.showToast({
          title: '转发成功',
          icon: 'success'
        })
      },
      fail: function(res) {
        //转发失败
      }
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    if (e.detail.errMsg != 'getUserInfo:ok') {
      wx.showModal({
        title: '提示',
        content: '您点击了拒绝授权，将无法显示个人信息',
        showCancel: false,
        confirmText: '知道了'
      })
    } else {
      wx.login({
        success: function(res) {
          console.log(res)
          var code = res.code;
        }
      })
      app.globalData.userInfo = e.detail.userInfo
      console.log(app.globalData.userInfo)
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
    }

  },
})